<?php

namespace api\lib;

class Http
{
    use ErrorLog;

    /**
     * @throws \ErrorException
     */
    public function post(/* string */ $url, /* array */ $params)
    {
        $ch = curl_init($url);
        if (substr($url, 0, 8) === 'https://') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        /** @var $ans string */
        $ans = curl_exec($ch);
        $errno = curl_errno($ch);
        if (0 != $errno) {
            $this->writeLog(curl_error($ch));
        }
        curl_close($ch);
        return $ans;
    }

    public static function buildQuery(array $para, $char = "&")
    {
        $arg = "";
        if ($para) {
            ksort($para);
            $params = [];
            foreach ($para as $key => $val) {
                $params[] = $key . "=" . urlencode($val);
            }
            $arg = implode($char, $params);
        }

        return $arg;
    }

}